##################################################
#     Name: module-gene split
#     Date: Jun 28, 2020
#     Author: Shawn Wang
#     Version: 0
##################################################
## options
args <- commandArgs(T)
wd <- args[1]
setwd(wd)
options(stringsAsFactors = F)
library(dplyr)
library(stringr)
## 
gene2mod <- read.delim("g2m.tmp",
                       sep = "\t",
                       header = T)
gene2mod = gene2mod[order(gene2mod[,2]),]
## The format of your input id GeneID or transcriptID
condition <- str_sub(gene2mod[1,1],-2,-2)
if (condition == ".") {
  geneid = sub(pattern = "..$",replacement = "",x = gene2mod[,1])
  out = data.frame(geneid = geneid,
                   module = gene2mod[,2])
  module = as.character(unique(out$module))
  mod = list()
  for (i in 1:length(module)) {
    mod[[i]] = filter(out, module == module[i])
    write.table(mod[[i]][,1], file = paste(wd,"/05.tmp/",module[i], sep = ""),
                sep = "\t",
                quote = F,
                row.names = F,
                col.names = F)
    }
}else{
  out <- gene2mod
  module = as.character(unique(out$Module))
  mod = list()
  for (i in 1:length(module)) {
    mod[[i]] = filter(out, Module == module[i])
    write.table(mod[[i]][,1], file = paste(wd,"/05.tmp/",module[i], sep = ""),
                sep = "\t",
                quote = F,
                row.names = F,
                col.names = F)
    }
}
